package org.codeart.sse.controller;

import lombok.extern.slf4j.Slf4j;
import org.codeart.common.util.R;
import org.codeart.common.util.SsePrefixUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
public class SseController {

    public static final Map<String, SseEmitter> sseEmitterMap = new HashMap<>();

    /**
     * 建立连接
     * @param userId 司机id
     */
    @GetMapping("/connect")
    public SseEmitter connect(@RequestParam("userId") Long userId, @RequestParam("identity") String identity) {
        log.info("用户 id: {}, 身份类型: {}", userId, identity);
        SseEmitter sseEmitter = new SseEmitter(0L);
        String mapKey = SsePrefixUtil.generateKey(userId, identity);
        sseEmitterMap.put(mapKey, sseEmitter);
        return sseEmitter;
    }

    /**
     * 推送消息
     * @param userId    用户id
     * @param identity  身份
     * @param content   内容
     */
    @GetMapping("/push")
    public R<String> push(@RequestParam("userId") Long userId, @RequestParam("identity") String identity,
                  @RequestParam("content") String content) {
        log.info("推送消息userId: {}, identity: {}, content: {}", userId, identity, content);
        String sseMapKey = SsePrefixUtil.generateKey(userId, identity);
        try {
            if (sseEmitterMap.containsKey(sseMapKey)) {
                sseEmitterMap.get(sseMapKey).send(content);
            } else {
                return R.fail("会话不存在");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok("给用户: " + sseMapKey + ", 发送了消息: " + content);
    }

    /**
     * 关闭连接
     * @param userId    用户id
     * @param identity  身份
     */
    @GetMapping("/close")
    public String close(@RequestParam("userId") Long userId, @RequestParam("identity") String identity) {
        String sseMapKey = SsePrefixUtil.generateKey(userId, identity);
        System.out.println("关闭连接: " + sseMapKey);
        sseEmitterMap.keySet().removeIf(id -> Objects.equals(id, sseMapKey));
        return "关闭成功";
    }

}
